import re
import json
from base.base_config import log, get_dingding_api
from common import utils

"""
基于项目不同场景的数据检查，可返回需要的数据
"""


# 检查请求后返回状态
def check_response_status(response, check=True, isprint=True, send_dingding=False):
    """
    检查请求后返回状态
    :param response: 响应信息
    :param check: 是否检查请求   True:检查   else:不检查
    :param isprint: 是否打印日志  True:打印   else:不打印
    :param send_dingding: 是否发送错误至钉钉 True:发送  else:不发送
    :return:
    """
    if check is True:
        # 传基础的响应参数
        if type(response) in (dict, str): raise TypeError("Please do not use res.json() and res.text,just use the res")

        try:
            assert response.status_code == 200
        except Exception as msg:
            log.error("状态码：{}，请检查！".format(response))
            raise Exception("状态码：{}，请检查！".format(response))
        else:
            error_code = re.search(r'"ErrorCode":"(\d+)"', response.text).group(1)

        url = response.request.url
        body = json.loads(response.request.body.decode()) if response.request.body else None
        headers = response.request.headers

        try:
            assert error_code == str(0)
            if isprint is True:
                log.info("请求接口:{0}, 返回响应信息:{1}".format(url, response.text))
        except Exception as msg:

            log.error("\n请求接口:{}\n请求头:{}\n请求数据:{}\n响应信息:{}".format(url, headers, body, response.text))

            if send_dingding is True:
                data = {
                    "msgtype": "markdown",
                    "markdown": {"title": "硬件接口测试",
                                 "text": "请求接口:{}  \n请求头:{}  \n请求数据:{}  \n响应信息:{}".format(url, headers, body, response.text)},
                    "at": {"isAtAll": False}  # True：通知所有人，False：不通知
                }
                utils.send_request(get_dingding_api(), datas=data)

            raise Exception("\n请求接口:{}\n请求头:{}\n请求数据:{}\n响应信息:{}".format(url, headers, body, response.text))
    else:
        print("不检查")


if __name__ == '__main__':
    pass
